# -*- coding: utf-8 -*-

from ftplib import FTP
import time
import os
import pexpect
import sys

serverip = 'serverip'
port = 22
username = ['username1','...']
password = ['password1','...']


dir_upload_name='download'

buf_size = 1024
fenshengfilename_Dict = {}

def putftpfile(ftp,localfilename,remotefilename):
    f_local_handler = open(localfilename,'rb')
    ftp.storbinary('STOR '+remotefilename,f_local_handler,buf_size)
    f_local_handler.close()

#自定义清洗函数（清洗本地文件）
def func_clean(filename):
    
    for sheng in username:
        fenshengfilename = sheng+'_'+str(time.strftime('%Y%m%d%H%M%S',time.localtime(time.time())))+'.txt'
        geshengfile = open(fenshengfilename,'w')
        fenshengfilename_Dict[sheng]=[fenshengfilename,geshengfile]
    
    with open(allshengfilename,'r') as geshengfile_handle:
        for line in geshengfile_handle.readlines():
            fenshengfilename_Dict[line.split(',')[-1].strip('\n')][1].write(line)
    
    for sheng in username:
        fenshengfilename_Dict[sheng][1].close()

        
def main():
    os.chdir('''/data/''')
    localtime = time.localtime()
    minutes = '00'
    if int(localtime.tm_min/15)== 0:
        minutes = '00'
    else:
        minutes = str(15*int(localtime.tm_min/15))
    
    hour = '0'
    if len(str(localtime.tm_hour))==1:
        hour = '0'+str(localtime.tm_hour)
    else:
        hour = str(localtime.tm_hour)
        
    allshengfilename = str(localtime.tm_year)+str(localtime.tm_mon)+str(localtime.tm_mday)+hour+minutes+str('00.txt')
    print(allshengfilename)
    func_clean(allshengfilename)
    
    for i in range(0,len(username)):
        ftp=FTP(serverip)
        ftp.set_debuglevel(2)
        ftp.login(username[i],password[i])
        ftp.cwd(dir_upload_name)
        filename = fenshengfilename_Dict[username[i]][0]
        if os.path.getsize(filename)==0:
            os.system('echo 0 > '+filename)
        putftpfile(ftp,filename,filename)
        
        ftp.quit()
    

if __name__=='__main__':
    main()


